﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using SDService.Common;
using SDService.Model;
using SDService.Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SDService.Controllers
{
    [Route("user/[controller]")]
    [ApiController]
    [ApiResultFilter]
    public class UserController : Controller
    {

        #region 初始化配置
        private readonly SDDBContext dbContext;

        public UserController(SDDBContext _context)
        {
            dbContext = _context;
        }
        #endregion

        #region 逻辑处理

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="request">登录信息</param>
        [HttpPost("Login")]
        public ResultResponseBase<LoginResponse> GetUserInfo(LoginRequest request)
        {
            if (string.IsNullOrEmpty(request?.LoginName))
                return ResponseBase.Error<ResultResponseBase<LoginResponse>>(30321, "用户名不可用空");

            if (string.IsNullOrEmpty(request?.Password))
                return ResponseBase.Error<ResultResponseBase<LoginResponse>>(30321, "密码不可用空");

            SDSysUsers user = dbContext.SystemUsers.FirstOrDefault(o => o.LoginName == request.LoginName && o.Password == request.Password);
            if (user == null)
                return ResponseBase.Error<ResultResponseBase<LoginResponse>>(30321, "用户名或密码错误");

            LoginResponse response = new LoginResponse();
            response.User = user;
            user.Password = "";

            var fes = from rva in dbContext.RoleVsApps
                      join r in dbContext.Appes on rva.AppCode equals r.AppCode
                      where rva.RoleCode == user.RoleCode
                      select new FunctionEntity
                      {
                          AppCode = r.AppCode,
                          AppId = r.Id.ToString(),
                          ClassInfo=new ClassInfo { DLLName=r.DllName, ClassFillName=r.ClassInfo },
                          FunctionType=(FunctionType)r.FunctionType,
                          ImagePath=r.ImagePath,
                          Title=r.AppName,
                          IsReload=r.IsReload,
                          ItemType= (FunctionItemType)r.FunctionType,
                          Status= (FunctionItemStatus)r.ItemStatus,
                          Index=r.IsIndex,
                          Parent=r.Parent,
                          Tip=new FunctionTip { Text = r.Tip, Title=r.AppName },
                          HotKey=r.HotKey
                      };
            response.Functions = fes.ToList();
            return new ResultResponseBase<LoginResponse> { Result = response };
        }


        #endregion

    }
}